<template>
  <el-dialog :title="!accountForm.id ? '新增用户' : '编辑用户'" :visible.sync="accountDialog">
    <el-form :model="accountForm" :rules="accountFormRules" ref="accountForm">
      <el-form-item label="登陆账号" :label-width="formLabelWidth" prop="username">
        <el-input v-model="accountForm.username"></el-input>
      </el-form-item>
      <el-form-item label="昵称" :label-width="formLabelWidth" prop="nickname">
        <el-input v-model="accountForm.nickname"></el-input>
      </el-form-item>
      <el-form-item v-show="!accountForm.id" label="密码" :label-width="formLabelWidth" prop="password">
        <el-input type="password" v-model="accountForm.password"></el-input>
      </el-form-item>
      <el-form-item label="用户角色" :label-width="formLabelWidth" prop="roleIds">
        <el-select v-model="accountForm.roleIds" multiple placeholder="请选择用户角色">
          <el-option v-for="item in roleList" :key="item.roleId" :label="item.name" :value="item.roleId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="用户头像" :label-width="formLabelWidth">
        <!--头像缩略图-->
        <pan-thumb :image="accountForm.avatar"></pan-thumb>
        <el-popover
            ref="picturePopover"
            placement="bottom-start"
            trigger="click"
            popper-class="mod-menu__icon-popover">
          <div class="mod-menu__icon-inner">
            <div class="mod-menu__icon-list">
              <el-image v-for="item in pictureList" :key="item.id"
                        :src="item.url"
                        @click="choosePicture(item)"
                        style="width: 100px; height: 100px;cursor:pointer" fit="scale-down"/>
            </div>
          </div>
        </el-popover>
        <el-button type="info" icon="el-icon-upload" circle v-popover:picturePopover></el-button>
        <el-input v-model="accountForm.avatar" placeholder="图片地址" readonly v-show="false"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="accountDialog = false">取 消</el-button>
      <el-button type="primary" @click="submit('accountForm')">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import PanThumb from '@/components/PanThumb'
import {userDetail, addUser, updateUser,checkName} from "@/api/system/user";
import {getRoleList} from "@/api/system/role";

export default {
  name: "account-add-or-update",
  components: {PanThumb},
  data() {
    let checkPassword = (rule, value, callback) => {
      if (this.accountForm.id) {
        callback()
      }else {
        if (!value) {
          return callback(new Error('密码不能为空'));
        } else {
          callback()
        }
      }
    };
    let checkUsername = (rule, value, callback) => {
      if (this.accountForm.id) {
        callback()
      }
      if (!value) {
        return callback(new Error('登陆账号不能为空'));
      } else {
        setTimeout(() => {
            checkName(value).then(res => {
              if (res.status && !res.data.isExist) {
                return callback(new Error('账号已存在'));
              }
              callback();
            })
        }, 100)
      }
    };
    return {
      accountForm: {
        username: '',
        nickname: '',
        password: '',
        userType: 2,
        roleIds: [],
        email: '',
        avatar: '',
      },
      accountDialog: false,
      pictureList: [],
      roleList: [],
      formLabelWidth: '80px',
      accountFormRules: {
        nickname: [
          {required: true, message: '请输入用户昵称', trigger: 'blur'},
        ],
        password: [
          {validator: checkPassword, required: true, trigger: 'blur'}
        ],
        username: [
          {validator: checkUsername, trigger: 'blur',required: true}
        ],
        roleIds: [
          {required: true, message: '请选择用户角色', trigger: 'change'}
        ]
      },
    }
  },
  methods: {
    init(id) {
      this.accountForm.id = id
      getRoleList().then(res => {
        this.roleList = res.data
      }).then(() => {
        this.accountDialog = true
        if (this.$refs['accountForm'] !== undefined) {
          this.accountForm.roleIds = []
          this.$refs['accountForm'].resetFields()
        }
      }).then(() => {
        if (this.accountForm.id) { //编辑
          userDetail(id).then(res => {
            this.accountForm = res.data
          })
        }
      })
      /*getPicture(0).then(res => {
        this.pictureList = res.data.data.pictureList
      }).then(() => {
        this.accountDialog = true
        if (this.$refs['accountForm'] !== undefined) {
          this.accountForm.roleIdList=[]
          this.$refs['accountForm'].resetFields()
        }
      }).then(() => {
        if (this.accountForm.id) { //编辑
          getUserById(id).then(res => {
            this.accountForm = res.data.data.user
          })
        }
      })*/
    },

    //选择照片
    choosePicture(data) {
      this.accountForm.avatar = data.url
    },

    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.accountForm.createUserId = this.$store.getters.id
          if (this.accountForm.id) { //修改
            delete this.accountForm.password
            updateUser(this.accountForm).then(res => {
              if (res.status) {
                this.$message.success('修改成功')
              } else {
                this.$message.error('修改失败')
              }
              this.accountDialog = false
              this.$emit('refreshDataList')
            })
          } else {
            addUser(this.accountForm).then(res => {
              if (res.status) {
                this.$message.success('添加成功')
              } else {
                this.$message.error('添加失败')
              }
              this.accountDialog = false
              this.$emit('refreshDataList')
            })
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    }
  },
}
</script>

<style scoped>

</style>
